<?php
namespace control;
/*
*取餐记录类
*/

use JetBrains\PhpStorm\NoReturn;

class takeMealRecordClass extends adIndexClass
{
    private const page = 'takeMealRecord';
    private const table = 'meal_take_record';
    private const table_report = 'meal_report';
    private const title = '取餐记录';
    public const reportOption = ['报餐', '代报餐', '申请客餐'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => '日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'hallId' => [
                        'name'  => "食堂名称",
                        'width' => 200,
                    ],
                    'mealType'  => [
                        'name'  => "餐别",
                        'width' => 200,
                    ],
                    'takeType'         => [
                        'name'  => '取餐类型',
                        'width' => 200,
                    ],
                    'staffId'          => [
                        'name'  => '员工',
                        'width' => 200,
                    ],
                    'num'          => [
                        'name'  => '份数',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'takeStid'          => [
                        'name'  => '取餐人',
                        'width' => 200,
                    ],
                    'takeTime'          => [
                        'name'  => '取餐时间',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "食堂名称" => selectMultiple(["name" => "hallId", 'table' => "dining_hall", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                    "餐别"     => select(array("name" => "mealType", "option" => explode("，", para("mealOption")))),
                    "报餐类型"     => select(array("name" => "type", "option" =>self::reportOption)),
                ],
                [
                    "员工" => selectMultiple(array("name" => "staffId", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200')),
                    "日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),

                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
        );
        //全等查询数组
        $equal = array(
            'b.type' => $this->post('type'),
            'b.staffId' => $this->post('staffId'),
            "b.hallId" => $this->post('hallId'),//食堂
            "b.mealType" => $this->post('mealType'),
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('time'), field: "b.recordDate");
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            'field'=>"b.*,a.takeStid,a.time as takeTime,a.type as takeType",
            "table" => self::table." as a join ".self::table_report." as b on a.reportId = b.id",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        static::rSet(self::$stid.self::page.'sql', $page['fullSql'], 3600*5); // 设置redis
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取表头
        $obj = new mealOrderRecordClass();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "hallId":
                        $row[] = $obj->hallName($array['hallId']);
                        break;
                    case "staffId":
                    case "takeStid":
                        $row[] = self::findStaff($array[$key]);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table." as a join ".self::table_report." as b on a.reportId = b.id",
            'single' => $where,
            'field'  => "ifnull(sum(b.num),0) as num",
        ]);
        $total    = [
            'num'        => $totalQuery['num'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
     public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            $obj = new mealOrderRecordClass();
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    'field'=>"b.*,a.takeStid,a.time as takeTime,a.type as takeType",
                    "table" => self::table." as a join ".self::table_report." as b on a.reportId = b.id",
                    "where" => "b.id in ('".implode("','", $checkedId)."') order by b.time desc",
                ))['array'];
            }else{
                $sql = static::rGet(self::$stid.self::page.'sql');
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '日期'=>$array['recordDate'],
                            '食堂名称'=>$obj->hallName($array['hallId']),
                            '餐别'=>$array['mealType'],
                            '取餐类型'=>$array['takeType'],
                            '员工'=> self::findStaff($array['staffId']),
                            '份数'=>$array['num'],
                            '取餐人'=>self::findStaff($array['takeStid']),
                            '取餐时间'=>$array['takeTime'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了取餐记录";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "取餐记录.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                ],
                [
                    'columnName'=>'食堂名称',
                    'aliasName'=>'食堂名称',
                ],
                [
                    'columnName'=>'餐别',
                    'aliasName'=>'餐别',
                ],
                [
                    'columnName'=>'取餐类型',
                    'aliasName'=>'取餐类型',
                ],
                [
                    'columnName'=>'员工',
                    'aliasName'=>'员工',
                ],
                [
                    'columnName'=>'份数',
                    'aliasName'=>'份数',
                ],
                [
                    'columnName'=>'取餐人',
                    'aliasName'=>'取餐人',
                ],
                [
                    'columnName'=>'取餐时间',
                    'aliasName'=>'取餐时间',
                ],
            ]
        };
    }
}

